package com.gyc.simple.userservices.controller;

import com.alibaba.fastjson.JSONObject;
import com.gyc.simple.common.util.DateUtils;
import com.gyc.simple.common.util.JwtUtils;
import com.gyc.simple.common.util.MD5Utils;
import com.gyc.simple.common.util.RedisUtils;
import com.gyc.simple.common.vo.ResponseType;
import com.gyc.simple.common.vo.User;
import com.gyc.simple.userservices.entity.base.IUser;
import com.gyc.simple.userservices.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


/**
 * @program: Inaction
 * @description: 登录处理
 * @author: Mr.gyc
 * @create: 2019-07-29 10:20
 */
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;
    //此处路径"/login" 验证是否登录filter使用修改请注意authfilter
    @PostMapping("/login")
    public ResponseType Login(@RequestBody IUser iuser){
        ResponseType responseType = new ResponseType();
        IUser dataUser = null;
        boolean flag = false;
        try{
            if(StringUtils.isNotBlank(iuser.getIuLname())){
               dataUser = userService.getUserByLoginName(iuser.getIuLname());
               if(dataUser!=null){
                   String passwordInfo = MD5Utils.getMD5String(iuser.getIuPassword()+ DateUtils.dateToString(dataUser.getIuRegistertime(),"yyyy-MM-dd HH:mm:ss"));
                   if(passwordInfo.equals(dataUser.getIuPassword())){
                       flag=true;
                       responseType.setData(JwtUtils.createTokenWithClaim(new User(dataUser.getIuId(),dataUser.getIuLname())));
                   }
               }
            }
        }catch (Exception e){
            responseType.setStatus(false);
            e.printStackTrace();
        }
        try {
            //登录成功转存用户信息到Redis缓存
            if(flag){
                RedisUtils.set("user_"+dataUser.getIuId(), JSONObject.toJSONString(dataUser));
            }
        }catch (Exception e){
            System.out.println("用户信息转存Redis失败！");
            e.printStackTrace();
        }
        return responseType;
    }


}
